<template>
  <div class="user-layout">
    <div class="user-lay-l">
      <Tree
        v-if="treeData.length"
        :tree-data="treeData"
        :replace-fields="replaceFields"
        :defaultExpandAll="true"
        @select="clickTreeNode"
      />
    </div>
    <div class="user-lay-r">
      <BasicTable
        @register="registerTable"
        @fetch-success="onFetchSuccess"
        ref="tableRef"
        :searchInfo="searchInfo"
      >
        <template #toolbar>
          <a-button
            type="primary"
            @click="handleCreate"
            v-if="hasPermission(['system:user:create'])"
          >
            新增
          </a-button>
          <a-button
            type="primary"
            color="warning"
            @click="handleExport"
            v-if="hasPermission(['system:user:export'])"
          >
            导出
          </a-button>
        </template>
        <template #status="{ record }">
          <!-- <Popconfirm
            title="Are you sure delete this task?"
            ok-text="Yes"
            cancel-text="No"
            :visible="popShow"
            @visible-change="handleVisibleChange($event, record)"
            @confirm="handleSwitch(record)"
          > -->
          <Switch
            v-model:checked="record.status"
            :checked-value="0"
            :un-checked-value="1"
            @change="SwitchChange($event, record)"
          />
          <!-- </Popconfirm> -->
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                ifShow: hasPermission(['system:user:update']),
              },
            ]"
            :dropDownActions="[
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                ifShow: hasPermission(['system:user:delete']),
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
              {
                label: '重置密码',
                icon: 'ant-design:redo-outlined',
                color: 'warning',
                onClick: handleReset.bind(null, record),
                ifShow: hasPermission(['system:user:update-password']),
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <Drawer @register="registerDrawer" @success="handleSuccess" :type="type" />
    <BasicModal v-bind="$attrs" @register="register" :title="modalTitle" @ok="resetPwd">
      <a-input-password
        v-if="modalTitle === '重置密码'"
        v-model:value="value.password"
        placeholder="请输入密码"
      />
    </BasicModal>
    <AssginRoleModal @register="registerRoleModal" @success="getTableList" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, toRefs, unref, ref } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction, TableActionType } from '/@/components/Table';
  import {
    getuser,
    adduser,
    edituser,
    deleteuser,
    updateUserStatus,
    resetpwd,
    getUserToken,
    deleteUserToken,
    exportUser,
    UserExportReqVO,
    getDeptList,
  } from '/@/api/backs/system/user';
  import { useDrawer } from '/@/components/Drawer';
  import Drawer from './components/Drawer.vue';
  import { Switch, message, Tree, Popconfirm } from 'ant-design-vue';
  import { columns, searchFormSchema } from './components/tableData';
  import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  import { onMounted } from 'vue';
  import AssginRoleModal from './components/AssginRoleModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  export default defineComponent({
    name: 'MenuManagement',
    components: {
      BasicTable,
      Drawer,
      TableAction,
      Switch,
      Tree,
      BasicModal,
      AssginRoleModal,
      Popconfirm,
    },
    setup() {
      const { hasPermission } = usePermission();
      let popShow = ref(false);
      let modalTitle = ref('重置密码');
      let value = reactive({
        password: '',
        id: null,
      });
      let roleForm = reactive({
        username: '',
        nickname: '',
        userId: null,
        roleIds: [],
        roleId: '',
      });
      const replaceFields = {
        children: 'children',
        title: 'name',
        key: 'id',
      };
      const treeData = ref<TreeDataItem[]>([]);
      const getDeptTree = async () => {
        treeData.value = await getDeptList({ status: 0 });
      };
      onMounted(() => {
        getDeptTree();
      });
      const clickTreeNode = (deptId = '') => {
        searchInfo.deptId = deptId[0];
        reload();
      };
      const tableRef = ref<Nullable<TableActionType>>(null);
      const getTableAction = () => {
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      };
      let listQuery = reactive({});
      const searchInfo = reactive<Recordable>({});
      const [registerDrawer, { openDrawer, closeDrawer }] = useDrawer();
      const [register, { openModal, closeModal, setModalProps }] = useModal();
      const [registerRoleModal, { openModal: openRoleModal }] = useModal();
      const [registerTable, { reload, setSelectedRowKeys, getForm }] = useTable({
        title: '用户列表',
        api: getuser,
        columns,
        formConfig: {
          labelWidth: 100,
          schemas: searchFormSchema,
        },
        rowKey: 'id',
        isTreeTable: false,
        beforeFetch: (params) => {
          if (params.createTime) {
            params.startTime = params.createTime[0];
            params.endTime = params.createTime[1];
            delete params.createTime;
          }
          listQuery = params;
        },
        pagination: true,
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        canResize: false,
        rowSelection: false,
        actionColumn: {
          title: '操作',
          width: 250,
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });
      const handleSwitch = (record) => {
        console.log(record);
      };
      const handleVisibleChange = (visible, e) => {
        // console.log(visible);
        // console.log(e); // 0 开启 1 关
        // if (visible) {
        //   e.status = 1;
        //   return;
        // }
        // if (e.status) {
        //   popShow.value = true;
        // } else {
        //   e.status = true;
        // }
      };
      const SwitchChange = async (e: any, record: any) => {
        let obj = { status: e ? 1 : 0, id: record.id };
        await updateUserStatus(obj);
        message.success('操作成功！');
      };
      const getSelectRowList = () => {
        return getTableAction().getSelectRows();
      };
      const setSelectedRowKeyList = (arr) => {
        setSelectedRowKeys(arr);
      };
      const data: any = reactive({
        type: 'add',
      });
      //编辑
      const handleEditSuccess = async (formData) => {
        let params = { ...formData };
        try {
          await edituser(params);
          closeDrawer();
          reload();
          message.success('操作成功！');
        } catch (error) {}
      };
      //新增
      const handleAddSuccess = async (formData) => {
        let params = { ...formData };

        try {
          await adduser(params);
          closeDrawer();
          reload();
          message.success('操作成功！');
        } catch (error) {}
      };
      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
        data.type = 'add';
      }
      async function handleExport() {
        await exportUser(getForm().getFieldsValue() as UserExportReqVO);
      }
      function handleEdit(record: Recordable) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
        data.type = 'edit';
      }
      function handleReset(record: Recordable) {
        value.password = '';
        modalTitle.value = '重置密码';
        openModal(true, record);
        const { id } = record;
        value.id = id;
      }
      const resetPwd = async () => {
        await resetpwd(value);
        closeModal();
        message.success('操作成功！');
        const data = await getUserToken({ userId: value.id });
        if (data?.list.length) {
          await deleteUserToken({ accessToken: data.list[0].accessToken });
        }
      };
      function handleAssign(record: Recordable) {
        openRoleModal(true, record);
      }
      const AssignRole = () => {};
      //删除
      const handleDelete = async (record: Recordable) => {
        try {
          await deleteuser({ id: record.id });
          reload();
          message.success('删除成功！');
        } catch (error) {}
      };

      function handleSuccess(formData) {
        switch (data.type) {
          case 'add':
            handleAddSuccess(formData);
            break;
          case 'edit':
            handleEditSuccess(formData);
            break;
        }
      }

      function onFetchSuccess() {}
      function getTableList() {
        message.success('操作成功！');
        reload();
      }
      return {
        ...toRefs(data),
        tableRef,
        registerTable,
        registerDrawer,
        registerRoleModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        onFetchSuccess,
        getSelectRowList,
        setSelectedRowKeyList,
        SwitchChange,
        handleSwitch,
        handleVisibleChange,
        // getDeptTree,
        treeData,
        replaceFields,
        handleReset,
        BasicModal,
        Tree,
        register,
        closeModal,
        openModal,
        setModalProps,
        value,
        resetPwd,
        clickTreeNode,
        searchInfo,
        handleAssign,
        AssignRole,
        roleForm,
        modalTitle,
        popShow,
        getTableList,
        listQuery,
        handleExport,
        hasPermission,
      };
    },
  });
</script>
<style lang="less">
  .user-layout {
    display: flex;
    .user-lay-l {
      width: 200px;
      background-color: #fff;
      margin: 16px;
      margin-right: 0;
      overflow-x: auto;
    }
    .user-lay-r {
      flex: 1;
    }
  }
</style>
